package com.xyz.async;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.concurrent.CompletableFuture;

@Service
public class AsyncService {

    private static final Logger logger = LoggerFactory.getLogger(AsyncService.class);

    @Async
    public void asyncMethodWithoutReturn() {
        try {
            // 模拟长时间运行的任务
            Thread.sleep(5000);
            logger.info("异步方法执行完成 - 无返回值");
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            logger.error("任务被中断", e);
        }
    }

    @Async
    public CompletableFuture<String> asyncMethodWithReturn() {
        try {
            // 模拟长时间运行的任务
            Thread.sleep(3000);
            logger.info("异步方法执行完成 - 有返回值");
            return CompletableFuture.completedFuture("Hello, Async World!");
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            logger.error("任务被中断", e);
            return CompletableFuture.completedFuture("Error occurred");
        }
    }
    @Async
    public CompletableFuture<Integer> processVideoToM3u8(String videoPath, String m3u8FilePath)
            throws IOException, InterruptedException {
        ProcessBuilder processBuilder = new ProcessBuilder();
        processBuilder.command("ffmpeg", "-i", videoPath,
                "-codec", "copy",
                "-start_number", "0",
                "-hls_time", "10",
                "-hls_list_size", "0",
                "-f", "hls",
                m3u8FilePath);

        Process process = processBuilder.start();
        int exitCode = process.waitFor();

        if (exitCode != 0) {
            throw new RuntimeException("ffmpeg转码失败，退出码：" + exitCode);
        }
        return CompletableFuture.completedFuture(exitCode);
    }
}